package com.ycsj.goldmedalnewconcept.teacher.activity;


import static com.blankj.utilcode.util.ToastUtils.showShort;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PickerManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LpUtils;
import com.ycsj.goldmedalnewconcept.student.bean.StHomeWorkInfo;
import com.ycsj.goldmedalnewconcept.teacher.adapter.HistoryWorkRvAdapter;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 历史练习
 * Created by Administrator on 2019/5/8 0008.
 */

public class TeacherHistoryHomeWorkActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srf)
    SmartRefreshLayout srf;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //定义上传服务器的时间,格式暂定为yyyy年-MM月
    private String time;

    //列表数据
    private List<StHomeWorkInfo.HomeworkBean> oldDatas;

    //空视图
    private View emptyView;

    //班级号
    private String classnum;

    //适配器
    private HistoryWorkRvAdapter adapter;


    /**
     * 跳转到当前界面的方法
     *
     * @param context
     * @param classnum
     */
    public static void goActivity(Context context, String classnum) {
        Intent it = new Intent(context, TeacherHistoryHomeWorkActivity.class);
        it.putExtra("classnum", classnum);
        context.startActivity(it);
    }


    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_history_homework;
    }

    @Override
    protected void setTitle() {
        super.setTitle();
        tvTitle.setText("历史课堂练习");
        lvEdit.setVisibility(View.VISIBLE);
        LpUtils.getRelatLp(UiUtils.dp2px(36), UiUtils.dp2px(36 * 3 / 2));
        lvEdit.setImageResource(R.drawable.img_cander);
    }

    @Override
    protected void init() {
        //初始化状态栏
        initStateBar();

        //初始化下拉刷新
        initSrf();

        //获取传递的班级
        initIntent();

        //设置查询的初始化时间
        initDate();

        //设置列表
        initRv();

        //请求数据
        http(BqaManager.NORML);
    }


    /**
     * 获取传递的班级号
     */
    private void initIntent() {
        classnum = getIntent().getStringExtra("classnum");
    }

    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, null);
    }

    /**
     * 设置列表
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("该月份暂时没有练习");
        adapter = new HistoryWorkRvAdapter(this, R.layout.history_rv_homework, oldDatas);
        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                //长按事件,布置在未来时间学生未收到之前是可以删除的,当前时间小于发送时间,长按删除
                if (System.currentTimeMillis() < DateUtils.getTime(oldDatas.get(position).getSended(), "yyyy-MM-dd HH:mm:ss")) {
                    //当前时间小于推送时间,可以删除
                    showDeletAction(position);
                }
                return true;
            }
        });
    }

    /**
     * 删除历史练习的操作
     *
     * @param position
     */
    private void showDeletAction(final int position) {
        PopUpManager.showPopByMatchParent(this, R.layout.pop_delete_history, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //取消
                Button btCancel = view.findViewById(R.id.bt_cancel);
                btCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopUpManager.dismiss();
                    }
                });

                //删除
                Button btDelete = view.findViewById(R.id.bt_delete);
                btDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopUpManager.dismiss();

                        CustomDialogManager.show(TeacherHistoryHomeWorkActivity.this, "删除中...");

                        StHomeWorkInfo.HomeworkBean homeworkBean = oldDatas.get(position);
                        Map<String, String> map = new HashMap<>();
                        map.put("type", "5");
                        map.put("acc", AccountUtils.getAccount(TeacherHistoryHomeWorkActivity.this));
                        map.put("role", AccountUtils.getRole(TeacherHistoryHomeWorkActivity.this));
                        map.put("workid", homeworkBean.getROW_ID() + "");
                        map.put("platform", "2");

                        HttpUtils.post(HttpAddress.DELETEHOMEWORK, map, TeacherHistoryHomeWorkActivity.this, new HttpUtils.CallBack() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                CustomDialogManager.dissmiss();
                                showShort(BaseApplication.ERROR + ",删除失败");
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                CustomDialogManager.dissmiss();

                                if (!TextUtils.isEmpty(response)) {
                                    ResultInfo info = null;
                                    try {
                                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                                    } catch (Exception e) {
                                        LogUtils.iTag(Constants.PARSEDATAERROR);
                                    }

                                    if (info != null) {
                                        if ("200".endsWith(info.getState())) {
                                            //移除删除位置的对象
                                            oldDatas.remove(position);
                                            //通知适配器刷新
                                            adapter.notifyItemRemoved(position);
                                            //解决位置错乱
                                            adapter.notifyItemRangeChanged(position, oldDatas.size() - position);
                                        } else {
                                            showShort("删除失败,异常码是:" + info.getState());
                                        }
                                    }
                                }
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 设置初始化查询时间
     */
    private void initDate() {
        time = DateUtils.getTime(new Date(), "yyyy-MM");
    }

    /**
     * 请求接口数据
     *
     * @param method
     */
    private void http(final int method) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("time", time);
        map.put("classnum", classnum);
        map.put("role", AccountUtils.getRole(this));
        map.put("platform", "2");

        LogUtils.iTag("test", HttpAddress.HISTORYWORKLIST + "&type=2&platform=2&acc="
                + AccountUtils.getAccount(this) + "&time=" + time + "&classnum=" + classnum
                + "role=" + AccountUtils.getRole(this));

        HttpUtils.post(HttpAddress.HISTORYWORKLIST, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {

                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(response)) {
                    StHomeWorkInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, StHomeWorkInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {

                            List<StHomeWorkInfo.HomeworkBean> newDatas = info.getHomework();
                            if (method == BqaManager.NORML) {
                                oldDatas.clear();
                                oldDatas.addAll(newDatas);
                                BqaManager.setRv(emptyView, TeacherHistoryHomeWorkActivity.this, adapter, rv);
                            } else {
                                BqaManager.updateRvBySmf(BqaManager.PULLREFRESH, srf, rv, oldDatas, newDatas, adapter);
                                if (method == BqaManager.PULLREFRESH) {
                                    adapter.setEnableLoadMore(false);
                                }
                            }
                        } else {
                            Log.i("test", "错误,状态码是:" + info.getState());
                        }
                    } else {
                        Log.i("test", "返回数据为空");
                    }
                } else {
                    Log.i("test", "返回数据为空");
                }
            }
        });
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:
                //选择日期
                showDatePick();
                break;
        }
    }

    /**
     * 选择日期的方法
     */
    private void showDatePick() {
        PickerManager.showPickerByYeaerAndMonth(this, new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //选中后的回调
                time = DateUtils.getTime(date, "yyyy-MM");
                http(BqaManager.NORML);
            }
        });
    }

    /**
     * 释放播放器
     */
    @Override
    protected void onDestroy() {
        adapter.releaseMediaPlayer();
        super.onDestroy();
    }
}
